package org.json;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static org.json.JsonObjectifier.*;

public class WildcardFinder {
    private JSONObject json;

    public WildcardFinder(JSONObject json) {
        this.json = json;
    }

    public List<Object> find(String wildcardName) {
        ArrayList<Object> accumulator = new ArrayList<Object>();
        find(wildcardName, json, accumulator);
        return accumulator;
    }

    private void find(String wildcardName, JSONObject parent, List<Object> accumulator) {
        Iterator children = parent.keys();
        while (children.hasNext()) {
            String key = (String) children.next();
            Object value = get(parent, key);
            if (wildcardName.equals(key)) {
                accumulator.add(value);
            } else {
                if (value instanceof JSONObject) {
                    find(wildcardName, (JSONObject) value, accumulator);
                } else if (value instanceof JSONArray) {
                    find(wildcardName, (JSONArray) value, accumulator);
                }
            }
            // ignore everything else (primitives)
        }
    }

    private void find(String wildcardName, JSONArray parent, List<Object> accumulator) {
        Iterator iterator = JsonObjectifier.iterable(parent).iterator();
        while (iterator.hasNext()) {
            Object child = iterator.next();
            if (child instanceof JSONObject) find(wildcardName, (JSONObject) child, accumulator);
        }
    }

}
